package cn.stylefeng.guns.modular.system.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.base.shiro.annotion.Permission;
import cn.stylefeng.guns.modular.system.entity.DispatchOrder;
import cn.stylefeng.guns.modular.system.entity.SendGoods;
import cn.stylefeng.guns.modular.system.mapper.InventoryOrderMapper;
import cn.stylefeng.guns.modular.system.model.params.SendGoodsParam;
import cn.stylefeng.guns.modular.system.model.result.resultVO.InventoryVO;
import cn.stylefeng.guns.modular.system.service.DispatchOrderService;
import cn.stylefeng.guns.modular.system.service.SendGoodsService;
import cn.stylefeng.guns.sys.core.shiro.ShiroKit;
import cn.stylefeng.guns.sys.core.util.utility.Katrina_CJ_Utils;
import cn.stylefeng.guns.sys.core.util.utility.Order;
import cn.stylefeng.guns.sys.core.util.utility.StatusCode;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;


/**
 * 发货单控制器
 *
 * @author 小飞
 * @Date 2019-07-17 02:59:22
 */
@Controller
@RequestMapping("/sendGoods")
public class SendGoodsController extends BaseController {

    private String PREFIX = "/sendGoods";

    @Autowired
    private SendGoodsService sendGoodsService;
    @Resource
    private TaskService taskService;
    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private DispatchOrderService dispatchOrderService;
    @Autowired
    private InventoryOrderMapper inventoryOrderMapper;

    private static  final  Logger LOGGER = LoggerFactory.getLogger(SendGoodsController.class);
    /**
     * 跳转到主页面
     *
     * @author 小飞
     * @Date 2019-07-17
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/sendGoods.html";
    }


    /**
     * 查看发货详情
     * @param inventoryIds
     * @return
     */
    @Permission
    @RequestMapping("/detail/{inventoryIds}")
    public String detail(@PathVariable  String inventoryIds){
        super.setAttr("inventoryIds",inventoryIds);
        super.setAttr("deptName",deptService.getById(ShiroKit.getUserNotNull().getDeptId()).getSimpleName());
        super.setAttr("username",ShiroKit.getUserNotNull().getId());
        return PREFIX + "/sendGoods_detail.html";
    }

    /**
     * 查看发货详情
     * @param inventoryIds
     * @return
     */
    @RequestMapping("/detailList/{inventoryIds}")
    public LayuiPageInfo detailList(@PathVariable  String inventoryIds){

        if (ToolUtil.isEmpty(inventoryIds)){
            Page page = LayuiPageFactory.defaultPage();
            Page<InventoryVO> pageUse = inventoryOrderMapper.getInventory(page,Katrina_CJ_Utils.getIds(inventoryIds));
            return  LayuiPageFactory.createPageInfo(pageUse);
        }else {
            LOGGER.info("传入id为空！");
            return new LayuiPageInfo();
        }

    }

    /**
     * 填写物流信息
     * @param taskId
     * @return
     */
    @RequestMapping("/addMessage")
    @Permission
    public String  writeMessage(String taskId){
        super.setAttr("taskId",taskId);
        return  PREFIX +"/sendGoods_message.html";
    };
    /**
     * 新增页面
     *
     * @author 小飞
     * @Date 2019-07-17
     */
    @RequestMapping("/add")
    public String add(Long id,String taskId) {
        super.setAttr("username",userService.getById(ShiroKit.getUserNotNull().getId()).getName());
        super.setAttr("deptName",deptService.getById(ShiroKit.getUserNotNull().getDeptId()).getSimpleName());
        super.setAttr("taskId",taskId);
        super.setAttr("id",id);
        return PREFIX + "/sendGoods_add.html";
    }

    /**
     * 编辑页面
     *
     * @author 小飞
     * @Date 2019-07-17
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/sendGoods_edit.html";
    }

    /**
     * 新增接口
     *
     * @author 小飞
     * @Date 2019-07-17
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(SendGoodsParam sendGoodsParam) {
        this.sendGoodsService.add(sendGoodsParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author 小飞
     * @Date 2019-07-17
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(SendGoodsParam sendGoodsParam) {
        this.sendGoodsService.update(sendGoodsParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author 小飞
     * @Date 2019-07-17
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(SendGoodsParam sendGoodsParam) {
        this.sendGoodsService.delete(sendGoodsParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author 小飞
     * @Date 2019-07-17
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(SendGoodsParam sendGoodsParam) {
        SendGoods detail = this.sendGoodsService.getById(sendGoodsParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author 小飞
     * @Date 2019-07-17
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(SendGoodsParam sendGoodsParam) {
        return this.sendGoodsService.findPageBySpec(sendGoodsParam);
    }

    /**
     * 提交操作
     * @param
     * @param id
     * @param taskId
     * @return
     */
    @RequestMapping("/submit")
    @ResponseBody
    public ResponseData submit(Long id,String taskId){

        SendGoods sendGoods = new SendGoods();
        StringBuilder idsss = new StringBuilder();
        /*List<SendGoodDTO> purchaseId = JSON.parseArray(sendGoodsParam.getPurchaseDetail(),SendGoodDTO.class);
        purchaseId.forEach(s -> idsss.append(s.getId()));
        sendGoods.setInventoryOrderId(idsss.toString());*/
        sendGoods.setCreateTime(new Date());
        sendGoods.setDispatchOrderId(id);
        sendGoods.setIsComplete(StatusCode.PENDING.getVal());
        SendGoods sendGoodsLast = sendGoodsService.getOne(new QueryWrapper<SendGoods>()
        .lambda().orderByDesc(SendGoods::getId).last("limit 1"));
        if (ToolUtil.isNotEmpty(sendGoodsLast)){
            sendGoods.setSendNum(Katrina_CJ_Utils.createOrderSerial(Order.FH_,sendGoodsLast.getId()));
        }else {
            sendGoods.setSendNum(Katrina_CJ_Utils.createOrderSerial(Order.FH_,(long)1));
        }
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        sendGoods.setProcessInstanceId(task.getProcessInstanceId());
        sendGoods.setUserId(ShiroKit.getUserNotNull().getId());
        sendGoodsService.save(sendGoods);
        taskService.complete(task.getId());
        return  ResponseData.success();
    }

    /**
     * 提交物流信息
     *
     * @param taskId
     * @param message
     * @return
     */
    @ResponseBody
    @RequestMapping("/submitMessage")
    public ResponseData addMessage(String taskId,String message){

        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        SendGoods sendGoods = sendGoodsService.getOne(new QueryWrapper<SendGoods>()
        .lambda().eq(SendGoods::getProcessInstanceId,task.getProcessInstanceId()));
        sendGoods.setLogistics(message);
        sendGoodsService.getBaseMapper().updateById(sendGoods);


        //同时更改申请发货单的申请信息
        DispatchOrder dispatchOrder = dispatchOrderService.getOne(new QueryWrapper<DispatchOrder>()
        .lambda().eq(DispatchOrder::getProcessInstanceId,task.getProcessInstanceId()));
        dispatchOrder.setDispatchCode(StatusCode.SENDHAVADOING.getVal());
        dispatchOrder.setCheckCode(StatusCode.SUCCESS.getVal());
        dispatchOrderService.getBaseMapper().updateById(dispatchOrder);

        taskService.complete(task.getId());
        return  ResponseData.success();
    }

    /**
     * 确认收货
     * @param id
     * @return
     */
    @RequestMapping("/recieve/{id}")
    public ResponseData recieve(Long id){
       SendGoods sendGoods = sendGoodsService.getById(id);
       sendGoods.setIsComplete(StatusCode.SUCCESS.getVal());
       sendGoodsService.getBaseMapper().updateById(sendGoods);
       return ResponseData.success();
    }

}


